package db0

import (
	"log"
	"path/filepath"
	"sync"

	"github.com/ungerik/go-dry"
	"gorm.io/gorm"
)

/*
可用`runtime.GOOS`判断操作系统 `go tool dist list`
os_type := runtime.GOOS -> if os_type == "windows" {
*/

var (
	once1    sync.Once
	dbpath01 = "./search_tool.db"
	db01     *gorm.DB
)

// init
func init() {
	// go tool dist list
	// os_type := runtime.GOOS -> if os_type == "windows" {
}

// Getdb
func Getdb() *gorm.DB {
	once1.Do(func() {
		// 检查当前目录下是否有`search_tool.db`文件
		path_in_current_folder := filepath.Join(".", "search_tool.db")
		db01 = common_get_db(path_in_current_folder, dbpath01)
	})
	return db01
}

/*
“获取数据库”通用方法
path_in_current_folder: 当前目录下的db文件
default_path: 默认db文件
*/
func common_get_db(path_in_current_folder, default_path string) *gorm.DB {
	var path string

	if dry.FileExists(path_in_current_folder) {
		path = path_in_current_folder
	} else {
		path = default_path
	}

	// panic: assignment to entry in nil map
	db, err := NewDbStore().GetByPath(path)
	if err != nil {
		log.Fatalf("连接数据库失败，(path=%s), %v", path, err)
	}

	return db
}
